<?php
class SurveysController extends AppController 
{

    public $sN = 'Survey'; 
    public $pN = 'survey';
    public $lN = 'surveys';    
    public $components = array("Emstraining","SendMail");
    public $paginate = array(
        'Survey' => array(
            'limit'      => '10'
        )
    );
    public function beforeFilter() {
        parent::beforeFilter();
        $this->set('sN', $this->sN);
        $this->set('pN', $this->pN);
        $this->set('lN', $this->lN);      
    }
    public function admin_index() {
        $this->loadModel("SurveyQuestion");
        $this->loadModel("Response");
        $values = $this->paginate($this->sN);
      	$this->set('values', $values);
    }
    public function index() {
        if(!$this->Auth->user("id")){
            $this->Session->setFlash("You must to login first!");
            $this->redirect("/");
        }
        $this->loadModel("Response");
        $surveys = array();
        $surveys = $this->Response->get_surveys_customer($this->Auth->user("id"));
        $this->loadModel("SurveyQuestion");
        $this->paginate = array(
            'Survey' => array(
                'status'      => '1'
            )
        );
        if(!empty($surveys)){
            $surveys = implode(",", $surveys);
            $values = $this->paginate($this->sN,array("Survey.id Not in ($surveys)",'status'=>1));
      	}else{
            $values = $this->paginate($this->sN,array('status'=>1));
        } 
        $this->set('values', $values);
    }
    public function view($survey_id=null){
        $this->loadModel("Response");
        $this->loadModel("Answer");
        $this->loadModel("SurveyQuestion");
        $check =$this->Response->check_survey_customer($survey_id,$this->Auth->user("id"));
        if($check==1){
            $this->Session->setFlash("Please choose another survey");
            $this->redirect("/");
        }
        $survey = $this->Survey->read(null,$survey_id);
        $this->set("survey",  $survey);
        if(!empty($_POST)){
            $this->loadModel("Response");
            $this->loadModel("ResponsesQuestionsOption");
            if($this->Auth->user('id')){
                $this->Response->create();
                $this->Response->save(array('created'=>date("Y-m-d H:i:s"),'survey_id'=>$survey_id,'customer_id'=>  $this->Auth->user("id")));
                $response_id = $this->Response->id ; 
                $right=0;
                $wrong = 0;
                $save_array = array();
                $save_array['response_id']=$response_id;
                foreach ($_POST['Question'] as $question_id => $value) {
                    $save_array['question_id']=$question_id;
                    if(is_array($value['answer'])){
                        foreach ($value['answer'] as $val) {
                            if($val=="other"){
                                $save_array['option_id']=0;
                                $save_array['extend']=$value['other'];
                            }else{
                                $save_array['option_id']=$val;
                            }
                            $this->ResponsesQuestionsOption->save($save_array);
                        }
                        if($survey['Survey']['type']==Survey::EXAMINATION){
                            $answer = $this->Answer->get_answers_by_questions($question_id);
                            $chk = 1;
                            foreach ($value['answer'] as $val) {
                                if(!in_array($val, $answer)){
                                    $chk=0;
                                }
                            }
                            if($chk==1){
                                $right++;
                            }else{
                                $wrong++;
                            }
                        }
                    }else{
                        if($value['answer']=="other"){
                            $save_array['option_id']=0;
                            $save_array['extend']=$value['other'];
                        }else{
                            $save_array['option_id']=$value['answer'];
                        }
                        if($survey['Survey']['type']==Survey::EXAMINATION){
                            $answer = $this->Answer->get_answers_by_questions($question_id);
                            if($answer[0]==$value['answer']){
                                $right++;
                            }else{
                                $wrong++;
                            }
                        }
                        $this->ResponsesQuestionsOption->save($save_array);
                    }
                }
                $this->loadModel("Customer");
                $customer = $this->Customer->read(null,$this->Auth->user("id"));
                $survey = $this->Survey->read(null,$survey_id);
                if($survey['Survey']['type']==Survey::INTVESTIGATE){
                    $this->Customer->id = $this->Auth->user("id");
                    $bal = $customer['Customer']['point']+$survey['Survey']['point_earned'];
                    $this->Customer->saveField('point',$bal);
                    $this->Session->setFlash("Thanks for your response ! {$survey['Survey']['point_earned']} point has been added to your balance");
                }elseif ($survey['Survey']['type']==Survey::EXAMINATION) {
                    
                    $this->Customer->id = $this->Auth->user("id");
                    
                    $questions = $this->SurveyQuestion->count_question_by_survey($survey_id);
                    
                    $point = $right*round($survey['Survey']['point_earned']/$questions);
                    
                    $bal = $customer['Customer']['point']+$point;
                    $this->Customer->saveField('point',$bal);
                    $this->Session->setFlash("You have completed the test <br/>Right Answer : $right <br/> Wrong Answer : $wrong <br/> {$point} point has been added to your balance");
                }
                
                $this->redirect(array('action'=>'index','admin'=>false));
            }else{
                $this->Session->setFlash("You must to login first");
                $this->redirect("/");
            }
        }
        $arr = array();
        $this->loadModel("SurveyQuestion");
        $this->loadModel("Question");
        $this->loadModel("QuestionOption");
        $values = array();
        if($survey_id){
            $cus = $this->SurveyQuestion->get_question_by_survey($survey_id);
            foreach ($cus as $q) {
                unset($q['SurveyQuestion']);
                $values[]=$q;
            }
        }
        $this->set("survey_id",$survey_id);
      	$this->set('values', $values);
    }
    public function admin_update_position($survey_id) {
        $this->autoRender=false;
        $this->loadModel("SurveyQuestion");
        if($this->request->is("ajax")){
            $i = 1;
            foreach ($_POST['data'] as $value) {
                if ($value){
                    $ids = explode("-", $value);
                    $this->SurveyQuestion->save_position($survey_id,$ids[1],$i);
                    $i++;
                }   
            }
        }
    }
    public function admin_questions($survey_id){
        $arr = array();
        $this->loadModel("SurveyQuestion");
        $this->loadModel("Question");
        $this->loadModel("QuestionOption");
        $this->loadModel("Answer");
        $values = array();
        if($survey_id){
            $cus = $this->SurveyQuestion->get_question_by_survey($survey_id);
            foreach ($cus as $q) {
                unset($q['SurveyQuestion']);
                $values[]=$q;
            }
        }
        $this->set("survey",  $this->Survey->read(null,$survey_id));
        $this->set("survey_id",$survey_id);
      	$this->set('values', $values);
    }
    public function admin_show_option(){
        $this->autoRender=false;
        if(isset($_REQUEST['query'])){
            $query = $_REQUEST['query'];
            
            $result=array();
            $this->loadModel('Option');
            $keywords = $this->Option->find('list',array('field'=>'title','conditions'=>array("title like '%$query%'")));
            foreach($keywords as $keyword){
                $result[]=$keyword;
            }
            header ('Content-Type: text/plain; charset=UTF-8');
            echo '{"query":'.'"'.$_REQUEST['query'].'","suggestions":["'.implode('","',$result).'"],"data":["'.implode('","',$result).'"]}';
        }
    }
    public function admin_save_question($survey_id,$question_id = null) {
        if($this->request->is("ajax")&&!empty($_POST)){
            $this->loadModel("SurveyQuestion");
            $this->loadModel("Question");
            $this->loadModel("QuestionOption");
            $this->loadModel("Option");
            $this->loadModel("Answer");
            if($this->Auth->user('id')){
                if($question_id){
                    if(!isset($_POST['has_other'])){
                        $_POST['has_other']=0;
                    }
                    $has_answer = 0;
                    if((isset($_POST['answers'])&&!empty($_POST['answers']))){
                        $has_answer=1;
                    }
                    $this->Question->id = $question_id;
                    
                    $this->Question->save(array('title'=>$_POST['title'],'has_answer'=>$has_answer,'has_other'=>$_POST['has_other'],'type'=>$_POST['type']));
                    if(!empty($_POST['option'])){
                        $this->QuestionOption->delete_options_by_question($question_id);
                        $this->Answer->delete_answers_by_question($question_id);
                        $i=0;
                        foreach ($_POST['option'] as $option) {
                            
                            $op = $this->Option->findByTitle(trim($option));
                            if(!empty($op)){
                                $option_id = $op['Option']['id'];
                            }else{
                                $this->Option->create();
                                $this->Option->save(array('title'=>$option));
                                $option_id = $this->Option->id;
                            }
                            if($has_answer==1){
                                if(in_array($i, $_POST['answers'])){
                                    $this->Answer->create();
                                    $this->Answer->save(array('question_id'=>$question_id,'option_id'=>$option_id));
                                }
                            }
                            
                            $this->QuestionOption->create();
                            $this->QuestionOption->save(array('question_id'=>$question_id,'option_id'=>$option_id));
                        
                            $i++;
                        }
                        $this->autoLayout=false;
                        $this->set("question",  $this->Question->read(null,$question_id));
                    }
                }else{
                    $this->Question->create();
                    $has_answer = 0;
                    if((isset($_POST['answers'])&&!empty($_POST['answers']))){
                        $has_answer=1;
                    }
                    $this->Question->save(array('created'=>date("Y-m-d H:i:s"),'title'=>$_POST['title'],'type'=>$_POST['type'],'has_answer'=>$has_answer,'has_other'=>$_POST['has_other'],'created_by'=>  $this->Auth->user('id')));
                    $question_id = $this->Question->id;
                    $this->SurveyQuestion->create();
                    $this->SurveyQuestion->save(array('surveys_id'=>$survey_id,'questions_id'=>$question_id));
                    if(!empty($_POST['option'])){
                        $i=0;
                        foreach ($_POST['option'] as $option) {
                            
                            $op = $this->Option->findByTitle(trim($option));
                            if(!empty($op)){
                                $option_id = $op['Option']['id'];
                            }else{
                                $this->Option->create();
                                $this->Option->save(array('title'=>$option));
                                $option_id = $this->Option->id;
                            }
                            if($has_answer==1){
                                if(in_array($i, $_POST['answers'])){
                                    $this->Answer->create();
                                    $this->Answer->save(array('question_id'=>$question_id,'option_id'=>$option_id));
                                }
                            }
                            $this->QuestionOption->create();
                            $this->QuestionOption->save(array('question_id'=>$question_id,'option_id'=>$option_id));
                        
                            $i++;
                        }
                        $this->autoLayout=false;
                        $this->set("question",  $this->Question->read(null,$question_id));
                    }
                }
            }else{
                $this->autoRender=false;
                return "error";
            }
            
        }
    }
    public function admin_add(){
        if(!empty($this->data)) {
            $this->request->data["Survey"]['created'] = date("Y-m-d H:i:s");
            $this->request->data["Survey"]['created_by'] = $this->Auth->user('id');
            $this->request->data['Survey']['status']=0;
            $this->Survey->create();
            
            if($this->Survey->save($this->data)) {
                $id = $this->Survey->id;
                $this->redirect(array('controller' => 'surveys', 'action' => 'questions',$id, 'admin' => true));
            }
        }
    }
    public function admin_edit($id=null){
        if(empty($this->data)) {
            $this->request->data = $this->Survey->read(null, $id);
        }else{
            $this->Survey->id = $id;
            if($this->Survey->save($this->data)) {
                $this->Session->setFlash(__('Updated Successfully', true));
                $this->redirect(array('controller' => 'surveys', 'action' => 'index', 'admin' => true));
            }
        }
    }
    public function admin_public($survey_id=null){
        if(!$survey_id){
            $this->Session->setFlash(__('Invalid Survey id', true));
            $this->redirect(array('controller' => 'surveys', 'action' => 'index', 'admin' => true));
        }else{
            $this->Survey->id = $survey_id;
            if($this->Survey->saveField('status',1)) {
                $this->loadModel("Customer");
                $customers = $this->Customer->find('all',array('conditions'=>array('Customer.status'=>1)));
                foreach($customers as $customer){
                    $this->SendMail->survey_added($customer['Customer']['email'],array('CUSTOMER_NAME'=>$customer['Customer']['f_name']." ".$customer['Customer']['l_name']));
                }
                $this->Session->setFlash(__('The survey now is active for customer', true));
                $this->redirect(array('controller' => 'surveys', 'action' => 'index', 'admin' => true));
            }
        }
    }
    public function admin_block($survey_id=null){
        if(!$survey_id){
            $this->Session->setFlash(__('Invalid Survey id', true));
            $this->redirect(array('controller' => 'surveys', 'action' => 'index', 'admin' => true));
        }else{
            $this->Survey->id = $survey_id;
            if($this->Survey->saveField('status',0)) {
                $this->Session->setFlash(__('The survey now is in-active for customer', true));
                $this->redirect(array('controller' => 'surveys', 'action' => 'index', 'admin' => true));
            }
        }
    }
    public function admin_question_form($survey_id,$question_id=null) {
        $this->loadModel("Question");
        $this->set("survey_id",$survey_id);
        $this->loadModel("Answer");
        if($question_id){
            $this->loadModel("QuestionOption");
            $this->loadModel("Option");
            $this->set("question", $this->Question->read(null,$question_id));
            $this->set("question_id",$question_id);
        }
        $this->autoLayout = false;
    }
    public function admin_question_form_exam($survey_id,$question_id=null) {
        $this->loadModel("Question");
        $this->loadModel("Answer");
        $this->set("survey_id",$survey_id);
        if($question_id){
            $this->loadModel("QuestionOption");
            $this->loadModel("Option");
            $this->set("question", $this->Question->read(null,$question_id));
            $this->set("question_id",$question_id);
        }
        $this->autoLayout = false;
    }
    public function admin_remove_question($survey_id,$question_id=null) {
        $this->loadModel("SurveyQuestion");
        $this->autoRender = false;
        if($this->Auth->user("id")){
            $this->SurveyQuestion->delete_survey_question($survey_id,$question_id);
            return "true";
        }else{
            return "error";
        }
    }
    public function admin_delete($id = null) {
        if(!$id){
            $this->Session->setFlash(__('Invalid Survey id', true));
            $this->redirect(array('controller' => 'surveys', 'action' => 'index', 'admin' => true));
        }else{
            $this->Survey->id = $id;
            if($this->Survey->delete()) {
                $this->loadModel("SurveyQuestion");
                $this->SurveyQuestion->delete_question_by_survey($id);
                $this->Session->setFlash(__('Survey has been deleted', true));
                $this->redirect(array('controller' => 'surveys', 'action' => 'index', 'admin' => true));
            }
        }
    }
}